package com.shawn.example.mvvmdemo.home.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.jetpack.mvvm.lib.net.module.HttpApiResult
import com.shawn.example.mvvmdemo.home.repository.WXRepository
import com.shawn.example.mvvmdemo.home.vo.FeedArticleData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class WxDetailViewModel @Inject constructor() : ViewModel() {
    companion object {
        private const val TAG = "WxDetailViewModel"
    }

    @Inject
    lateinit var repository: WXRepository
    private val detailListLiveData = MutableLiveData<List<FeedArticleData>>()
    private var authorId: Int = 0
    val detailLV: LiveData<List<FeedArticleData>> = detailListLiveData

    fun getAuthorWxArticles(authorId: Int, curPage: Int) = viewModelScope.launch(Dispatchers.Default) {
        Log.e(TAG, "$authorId  $curPage  ${this@WxDetailViewModel::repository.isInitialized}")
        this@WxDetailViewModel.authorId = authorId
        val articleList = repository.getWxArticlesList(authorId, curPage)
        if (articleList.isSuccess) {
            val data = (articleList as HttpApiResult.Success).value
            if (curPage <= 1) {
                detailListLiveData.postValue(data.datas)
            } else {
                val list = mutableListOf<FeedArticleData>()
                detailListLiveData.value.takeIf { !it.isNullOrEmpty() }?.let {
                    list.addAll(it)
                }
                list.addAll(data.datas)
                detailListLiveData.postValue(list)
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        Log.e(TAG, "onCleared $authorId")
    }
}